import time

from django.conf import settings
from django.db import transaction
from django.db.models import Q
from django.http import JsonResponse
from django.utils import timezone
from django.views import View
import json
import datetime
from homes.models import Area, House, HouseImage
from order.models import Order
from users.models import User
from utils.view import LoginRequiredMixin

import logging
logger = logging.getLogger('django')


class OrdersView(LoginRequiredMixin,View):
    # 增加订单
    def post(self,request):
        json_dict = json.loads(request.body.decode())
        house_id=json_dict.get('house_id')
        start_date = json_dict.get('start_date')
        end_date = json_dict.get('end_date')
        user = request.user
        if not all([house_id, start_date, end_date]):
            return JsonResponse({'errno': 400, 'errmsg': '缺少必传参数'})
        try:
            house = House.objects.get(id=house_id)
        except Exception as e:
            return JsonResponse({'errno': 400, 'errmsg': '参数house_id错误'})
        if user==house.user:
            return JsonResponse({'errno': 400, 'errmsg': '不能预定自己的房源'})
        try:
            orders = Order.objects.filter(begin_date__lt=end_date, end_date__gt=start_date, house=house)
        except Exception as e:
            return JsonResponse({'errno': 400,
                                 'errmsg': '数据库查询错误'})
        if orders:
            return JsonResponse({'errno': 400,
                                 'errmsg': '已经被预定'})
        date1 = time.strptime(start_date, "%Y-%m-%d")
        date2 = time.strptime(end_date, "%Y-%m-%d")
        date1 = datetime.datetime(date1[0], date1[1], date1[2])
        date2 = datetime.datetime(date2[0], date2[1], date2[2])
        days=date2-date1
        days=days.days
        if house.max_days==0 and house.min_days<=days:
            try:
                order = Order.objects.create(user=user, house=house, begin_date=start_date,
                                             end_date=end_date, days=days, house_price=house.price,
                                             amount=days * house.price,
                                             status=Order.ORDER_STATUS["WAIT_ACCEPT"])
            except Exception as e:
                return JsonResponse({'errno': 400,
                                     'errmsg': '创建订单失败'})
            try:
                house.order_count += 1
                house.save()
            except Exception as e:
                return JsonResponse({'errno': 400,
                                     'errmsg': '增加房屋订单数量失败'})
            return JsonResponse({"data": {"order_id": order.id},
                                 "errno": "0",
                                 "errmsg": "下单成功"})
        if house.min_days<=days<=house.max_days:
            try:
                order = Order.objects.create(user=user, house=house, begin_date=start_date,
                                             end_date=end_date, days=days, house_price=house.price,
                                            amount=days * house.price,
                                             status=Order.ORDER_STATUS["WAIT_ACCEPT"])
            except Exception as e:
                return JsonResponse({'errno': 400,
                                     'errmsg': '创建订单失败'})
            try:
                house.order_count += 1
                house.save()
            except Exception as e:
                return JsonResponse({'errno': 400,
                                     'errmsg': '增加房屋订单数量失败'})
            return JsonResponse({"data": {"order_id": order.id},
                                 "errno": "0",
                                 "errmsg": "下单成功"})
        else:
            return JsonResponse({'errno': 400,
                                 'errmsg': '预定失败'})

    def get(self, request):
        """获取订单列表功能"""
        role = request.GET.get('role')
        user = request.user
        print(role)
        orders_list = []
        if role == 'custom':
            try:
                orders = Order.objects.filter(user=user)
            except Exception as e:
                return JsonResponse({'errno': 400,
                                     'errmsg': '数据库查询错误'})
        elif role == 'landlord':
            try:
                houses = House.objects.filter(user=user)
                orders = Order.objects.filter(house__in=houses)
            except Exception as e:
                return JsonResponse({'errno': 400,'errmsg': '数据库查询错误'})
        else:
            return JsonResponse({'errno': 400, 'errmsg': '参数错误'})

        for order in orders:
            if order.status == Order.ORDER_STATUS["WAIT_COMMENT"]:
                if role == 'landlord':
                    status = 'ACCEPT'
                else:
                    status = Order.ORDER_STATUS_ENUM[order.status]
            else:
                status = Order.ORDER_STATUS_ENUM[order.status]
            orders_list.append({
                "amount": order.amount,
                "comment": order.comment,
                "ctime": order.create_time,
                "days": order.days,
                "end_date": order.end_date,
                "img_url": settings.QINIU_URL+order.house.index_image_url,
                "order_id": order.id,
                "start_date": order.begin_date,
                "status": status,
                "title": order.house.title})
            # 3. 返回参数
        return JsonResponse({"data": {"orders": orders_list},
                             "errmsg": "OK",
                             "errno": "0"})


class OrdersStatusView(View):

    """接单和拒单功能"""
    def put(self, request, order_id):
        json_dict = json.loads(request.body.decode())
        action = json_dict.get('action')
        reason = json_dict.get('reason')
        if not all([action, order_id]):
            return JsonResponse({'errno': 400, 'errmsg': '参数错误'})
        if action == 'reject':
            if not all([reason]):
                return JsonResponse({'errno': 400, 'errmsg': '拒单原因参数错误'})
            try:
                order =Order.objects.filter(id=order_id)
                order.update(comment=reason, status=Order.ORDER_STATUS['REJECTED'])
                house = House.objects.filter(id=order.house_id)
            except Exception as e:
                logging.error(e)
                return JsonResponse({'errno': 400, 'errmsg': '数据库查询失败'})
            try:
                house.order_count -= 1
                house.save()
            except Exception as e:
                return JsonResponse({'errno': 400,
                                     'errmsg': '增加房屋订单数量失败'})
        elif action == 'accept':
            try:
                order = Order.objects.filter(id=order_id)
                order.update(status=Order.ORDER_STATUS['WAIT_COMMENT'])
            except Exception as e:
                logging.error(e)
                return JsonResponse({'errno': 400, 'errmsg': '数据库操作失败'})

        else:
            return JsonResponse({'errno': 400, 'errmsg': '参数错误'})
        return JsonResponse({'errno': 0, 'errmsg': '操作成功'})



class OrdersCommentView(View):

    """评论订单功能"""
    def put(self, request, order_id):
        json_dict = json.loads(request.body.decode())
        comment = json_dict.get('comment')
        if not all([comment]):
            return JsonResponse({'errno': 400, 'errmsg': '参数错误'})
        try:
            order = Order.objects.filter(id=order_id)
            order.update(comment=comment, status=Order.ORDER_STATUS['COMPLETE'])
        except Exception as e:
            logging.error(e)
            return JsonResponse({'errno': 400, 'errmsg': '数据库查询失败'})

        return JsonResponse({'errno': 0, 'errmsg': '操作成功'})

























